﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Reflection;

namespace CrusadeGmTool.Controls
{
    class ReadOnlyPropertyGrid : PropertyGrid
    {
        private bool _readonly;

        public bool IsReadOnly
        {
            get { return _readonly; }
            set
            {
                this._readonly = value;
                this.SetBrowsablePropertiesAsReadOnly(this.SelectedObject, value);
            }
        }

        protected override void OnSelectedObjectsChanged(EventArgs e)
        {
            this.SetBrowsablePropertiesAsReadOnly(this.SelectedObject, this.IsReadOnly);
            base.OnSelectedObjectsChanged(e);
        }
        public ReadOnlyPropertyGrid()
            : base()
        {
        }

        /// <summary>
        /// Chnages the state of the ReadOnly attribute regarding the isReadOnly flag value.
        /// </summary>
        /// <param name="selectedObject">The current object</param>
        /// <param name="isReadOnly">current state</param>
        private void SetBrowsablePropertiesAsReadOnly(object selectedObject, bool isReadOnly)
        {
            if (SelectedObject != null)
            TypeDescriptor.AddAttributes(this.SelectedObject, new Attribute[] { new ReadOnlyAttribute(isReadOnly) });
            //if (selectedObject != null)
            //{
            //    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(selectedObject.GetType());
            //    foreach (PropertyDescriptor property in props)
            //    {
            //        if (property.IsBrowsable && property.PropertyType.GetInterface("ICollection", true) == null)
            //        {
            //            ReadOnlyAttribute attr = property.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
            //            if (attr != null)
            //            {
            //                FieldInfo field = attr.GetType().GetField("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
            //                field.SetValue(attr, isReadOnly, BindingFlags.Instance | BindingFlags.NonPublic, null, null);
            //            }
            //        }
            //    }
            //}
        }

    }
}
